# -*- coding: utf-8 -*-

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from pprint import  pprint


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()

        self.name = "横琴优康保终身重大疾病保险"

    # 生成产品信息
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(1, 41)],
                # 性别
                "gender": ["M", "F"],
                # 缴费间隔
                "interval": ["0", "3", "5", "10", "15", "20", "30"],
                # 保费
                "money": ["50000", "150000", "200000", "300000"],
                # 保障期限
                "expire": ["终身"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 缴费间隔
                "interval": ["0", "3", "5", "10", "15", "20", "30"],
                # 保费
                "money": ["50000", "150000", "300000"],
                # 保障期限
                "expire": ["终身"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 缴费间隔
                "interval": ["0", "3", "5", "10", "15", "20"],
                # 保费
                "money": ["50000", "150000"],
                # 保障期限
                "expire": ["终身"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 缴费间隔
                "interval": ["0", "3", "5", "10", "15", "20"],
                # 保费
                "money": ["50000"],
                # 保障期限
                "expire": ["终身"]
            },
        }
        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["interval"], plan[k]["money"],
                             plan[k]["expire"]):

                if v[2] == "0":

                    payType = "一次缴清"

                else:

                    payType = "年缴"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], payType, v[4]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], payType, v[4]
                ))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"saleItemId": 10024, "birthDate": "{year}-01-01".format(year = str(2020-int(dt["year"]))), "gender": dt["gender"], "sumAssured": dt["money"],
                "premPeriodNumber": "to_full" if dt["interval"] =="0" else "term_"+dt["interval"], "policyPeriodNumber": "to_full" , "provinceCode": "440000",
                "cityCode": "445200", "urbanAreaCode": "445281"}
        payload = json.dumps(data)

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        pprint( r.json() )
        if r.status_code == 200 and r.json()["success"]:

            price = Helper.decimalParse(r.json()["data"]["totalPermium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )

            print("/*产品价格信息更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )
